package qqhfpay

import (
	"context"
	"errors"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/logic/pay"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/pay/qqhfpay"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/consts"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/bytedance/sonic"
	"github.com/bytedance/sonic/decoder"
	"github.com/zeromicro/go-zero/core/logc"

	"github.com/zeromicro/go-zero/core/logx"
)

type QQHPaymentNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// starpay代收回调通知
func NewQQHPaymentNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QQHPaymentNotifyLogic {
	return &QQHPaymentNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QQHPaymentNotifyLogic) QQHPaymentNotify(req *types.QQHPaymentNotifyReq) (resp *types.QQHPPaymentNotifyResp, err error) {
	// 回调信息转为 json 字符串
	b, _ := sonic.Marshal(req)
	logc.Info(l.ctx, string(b))
	var data map[string]any
	dc := decoder.NewDecoder(string(b))
	dc.UseNumber()
	if err = dc.Decode(&data); err != nil {
		logc.Error(l.ctx, err, string(b))
		return nil, err
	}

	// 获取  配置信息
	conf, err := l.svcCtx.AssetsRpc.PayRecharge.RechargeChannelListByCode(l.ctx, &rpc.RechargeChannelByCodeRequest{Code: consts.QqhfpayCode})
	if err != nil {
		logc.Error(l.ctx, err, string(b))
		return nil, err
	}

	// 验签
	if req.Sign != "" {
		qqhf, err := qqhfpay.GenerateSignatureOfQqhf(data, conf.SecretKey)
		if err != nil {
			logc.Error(l.ctx, err, string(b))
			return nil, err
		}
		if qqhf != req.Sign {
			logc.Error(l.ctx, "signature verification failed: ", qqhf, req.Sign)
			return nil, errors.New("signature verification failed")
		}
	}

	// 根据订单状态处理业务逻辑
	switch req.Status {
	case "SUCCESS":
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeSuccess(l.ctx, &rpc.NotifyOKRequest{OrderNo: req.SysOrderId, ReturnJson: string(b)})
		if err != nil {
			logc.Error(l.ctx, err, string(b))
			return
		}
		pay.NewHandleOrderLogic(l.ctx, l.svcCtx).AddNotifitionMessage(&pay.NotifyMessageInfo{OrderNo: req.SysOrderId})

	case "FAIL":
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeFail(l.ctx, &rpc.NotifyFailRequest{OrderNo: req.SysOrderId, ReturnJson: string(b)})
		if err != nil {
			logc.Error(l.ctx, err, string(b))
			return
		}
	default:
	}
	resp.Ok = true
	return
}
